import {makeAutoObservable, runInAction} from 'mobx'
import {getPreAuthVO} from "@/services/OpenService";
import {MpVO} from "@/services/MpService";
import {request} from "@umijs/max";

export interface UpdateMiniappDTO {
    appId: string;
    avatar: string;
    templateId: number;
    nickName: string;
    idCard: string;
    license: string;
    signature: string;
}

class MpModel {
    // 授权url
    authUrl?: string
    createMiniappModelState = false
    current: MpVO = {type: "", appId: "", id: 0}
    uploadLoading = true;
    avatarUrl: string = 'https://leuan.top/files/2023/03/29/tmp_882cb193cfcb54d0d0071671d4a6554b.jpg';

    constructor() {
        makeAutoObservable(this, {}, {autoBind: true})
    }

    changeCreateMiniappModel(state: boolean) {
        this.createMiniappModelState = state
    }

    /**
     * 打开创建小程序模态框
     */
    openCreateMiniappModel(current: MpVO) {
        this.current = current
        this.createMiniappModelState = true
    }

    /**
     * 关闭创建小程序模态框
     */
    closeCreateMiniappModel() {
        this.createMiniappModelState = false
    }

    /**
     * 跳转到预授权URL
     */
    async goToAuthUrl() {
        let res = await getPreAuthVO()
        runInAction(() => {
            this.authUrl = res.preAuthUrl
            window.open(res.preAuthUrl)
        })
    }

    async updateMiniapp(data: UpdateMiniappDTO) {
        data.avatar = this.current.headImg || ''
        return request<any>(`/api/open/setMiniapp`, {method: 'POST', data})
    }

    handlerImageUpload(info:any) {
        console.log(info)
        if (info.file.status === 'done') {
            this.current.headImg = info.file.response.data[0].url
        }
    }
}

export default MpModel
export const mpModel = new MpModel()
